package daobeauty.proxy.spring;

import java.util.Collection;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ListableBeanFactory;

/**
 * Created 09.09.2008
 * @author M. Serhat Cinar
 *
 */
public class DaoBeautyInterceptor implements MethodInterceptor, InitializingBean, BeanFactoryAware {
	private daobeauty.interceptor.MethodInterceptor generalMethodInterceptor = new daobeauty.interceptor.MethodInterceptor();
	private BeanFactory beanFactory;
	
	public DaoBeautyInterceptor(){}
	
	public void setDelegates(Collection delegates){
		generalMethodInterceptor.setDelegates(delegates);
	}
	
	public void setTarget(Object target){
		generalMethodInterceptor.setTarget(target);
	}
	
	public void setDomainClass(Class domainClass) {
		generalMethodInterceptor.setDomainClass(domainClass);
	}
	
	public void setSessionFactory(SessionFactory sessionFactory){
		generalMethodInterceptor.setSessionFactory(sessionFactory);
	}
	
	public void setInterfaces(Class [] interfaces){
		generalMethodInterceptor.setInterfaces(interfaces);
	}
	
	/* (non-Javadoc)
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
	 */
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		return generalMethodInterceptor.invoke(methodInvocation.getMethod(), methodInvocation.getArguments());
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		if (generalMethodInterceptor.getSessionFactory()==null && beanFactory.containsBean("sessionFactory")){
			generalMethodInterceptor.setSessionFactory((SessionFactory)beanFactory.getBean("sessionFactory"));
		}
		if (generalMethodInterceptor.getSessionFactory()==null && beanFactory instanceof ListableBeanFactory) {
			final ListableBeanFactory lbf = (ListableBeanFactory) beanFactory;
			SessionFactory sf = (SessionFactory) BeanFactoryUtils.beanOfTypeIncludingAncestors(lbf, SessionFactory.class);
			generalMethodInterceptor.setSessionFactory(sf);
		}
		generalMethodInterceptor.initialize();
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
	 */
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

}
